<template lang="pug">
.page
  .CustomerBill
    .search-form.mb-25.pl-10.pr-10
      Row.mb-15(type="flex" justify="start")
        Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 10 }" :xxl="{span: 8}")
          span.label-txt.w80 查询单位：
          Select(v-model="formData.customerIds" multiple :max-tag-count="2" filterable @on-change="handleCustomerIdsChange")
            Option(v-for="(c_item, c_index) of arrListDown.customer" :key="c_index" :value="c_item.value") {{c_item.label}}
        Col.pr-20.mb-10(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 4 }" :xxl="{span: 4}")
          Button(@click="handleShowChooseCustomerModal") 批量选择单位
        Col.pr-20(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 8 }" :xxl="{span: 6}")
          span.label-txt.w80 费用月份：
          DatePicker.pull-left.interval-date-140(:value="formData.beginTime" placeholder="开始日期" type="month" @on-change="handleChangeDatePicker('beginTime', $event)")
          span.pl-10.pr-10.pull-left.line-h-32 --
          DatePicker.pull-left.interval-date-140.mr-20(:value="formData.endTime" placeholder="结束日期" type="month" @on-change="handleChangeDatePicker('endTime', $event)")
        Col(:md="{ span: 24 }" :lg="{ span: 12 }" :xl="{ span: 4 }" :xxl="{span: 4}")
          Button.h32(type="info" @click="searchFn") 查询

    .pl-20.pr-20.bg-white
      Table.ivu-table-overflowY-hidden.beautiful-table(:columns="thead" :data="tableData" :stripe="true" v-show="isShowTable")
        .clearfix.font-16(slot="header")
            //- .table-title-lefttxt.pull-left
            //-   |合计
            //-   span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
            //-   |条
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasExportCustomerSummary" type="info" @click="handleExportCustomerSummary") 导出客户数据汇总
              Button.mr-10(v-if="hasExportCustomerSummaryDetail" type="info" @click="handleShowExportProjectModal") 导出客户数据明细
              Button.mr-10(v-if="hasExportEmployeeSummary" type="info" @click="handleShowExportEmployeeModal(3, 'summary')") 导出员工数据汇总
              Button(v-if="hasExportEmployeeSummaryDetail" type="info" @click="handleShowExportEmployeeModal(4, 'detail')") 导出员工数据明细

        template(slot-scope="{ row, index }" v-for="item in slotArr" :slot="item.slot")
          //- Button(v-if="item.slot === 'shenqingkaipiao' && hasPostInvoice" :type="item.type" size="small" @click="listenCall(item.fn, row)" :disabled="row.isInvoice || !row.isVerified") {{item.text}}
          Button(:type="item.type" size="small" @click="listenCall(item.fn, row)") {{item.text}}
        template(slot-scope="{ row, index }" v-for="item in slotArr" slot="shujuhedui")
          Button(v-if="hasBillCheck" type="info" size="small" @click="listenCall('handleShowDatacheckModal', row)" :disabled="row.isVerified") 核对完成
        template(slot-scope="{ row, index }" v-for="item in slotArr" slot="shenqingkaipiao")
          Button(v-if="hasPostInvoice" type="info" size="small" @click="listenCall('handleShowApplyInvoiceModal', row)" :disabled="row.isInvoice || !row.isVerified") 申请开票
        .clearfix.pl-20.pr-20(slot="footer")
          Page(
            :current="tableComone.pageIndex"
            :total="tableComone.totalRows"
            @on-change="onChangePage"
            @on-page-size-change="onpageSizeChange"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )

    //- 服务费汇总表格弹窗
    TableFuwufeihuizongModal(ref="TableFuwufeihuizongModal")
    //- 服务费明细表格弹窗
    TableFuwufeimingxiModal(ref="TableFuwufeimingxiModal")
    //- 薪资明细表格弹窗
    TableXinzimingxiModal(ref="TableXinzimingxiModal" @handleShowChooseExportTemplateModal="handleShowChooseExportTemplateModal")
    //- 商保明细表格弹窗
    TableShangbaomingxiModal(ref="TableShangbaomingxiModal")
    //- 公积金明细表格弹窗
    TableGongjijinmingxiModal(ref="TableGongjijinmingxiModal")
    //- 社保明细表格弹窗
    TableShebaomingxiModal(ref="TableShebaomingxiModal")
    //- 社保汇总表格弹窗
    TableShebaohuizongModal(ref="TableShebaohuizongModal")
    //- 汇总报表表格弹窗
    TableHuizongbaobiaoModal(ref="TableHuizongbaobiaoModal")
    //- 明细汇总表格弹窗
    TableMingxihuizongModal(ref="TableMingxihuizongModal")

    //- 选择单位弹窗
    ChooseCustomerModal(ref="ChooseCustomerModal" @chooseSubmit="chooseSubmit")

    //- 导出客户数据前弹窗
    ExportProjectModal(ref="ExportProjectModal")
    //- 导出员工数据前弹窗
    ExportEmployeeModal(ref="ExportEmployeeModal")
    
    //- 选择导出模板弹窗
    ChooseExportTemplateModal(ref="ChooseExportTemplateModal" @handleShowChooseExportTemplateModal="handleShowChooseExportTemplateModal" @chooseTemplate="chooseTemplate")
</template>

<script>
import { MergeBillApi } from '@/api/MergeBill.api.js'
import { billMergeThead } from './CBMtableHead.js'
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import TableFuwufeihuizongModal from './modal/tableFuwufeihuizongModal.vue'
import TableFuwufeimingxiModal from './modal/tableFuwufeimingxiModal.vue'
import TableXinzimingxiModal from './modal/tableXinzimingxiModal.vue'
import TableShangbaomingxiModal from './modal/tableShangbaomingxiModal.vue'
import TableGongjijinmingxiModal from './modal/tableGongjijinmingxiModal.vue'
import TableShebaomingxiModal from './modal/tableShebaomingxiModal.vue'
import TableShebaohuizongModal from './modal/tableShebaohuizongModal.vue'
import TableHuizongbaobiaoModal from './modal/tableHuizongbaobiaoModal.vue'
import TableMingxihuizongModal from './modal/tableMingxihuizongModal.vue'
import ChooseCustomerModal from './modal/chooseCustomerModal.vue'
import ExportProjectModal from './modal/exportProjectModal.vue'
import ExportEmployeeModal from './modal/exportEmployeeModal.vue'
import ChooseExportTemplateModal from '../publicModal/chooseExportTemplateModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'CustomerBillMerge',

  components: {
    TableFuwufeihuizongModal,
    TableFuwufeimingxiModal,
    TableXinzimingxiModal,
    TableShangbaomingxiModal,
    TableGongjijinmingxiModal,
    TableShebaomingxiModal,
    TableShebaohuizongModal,
    TableHuizongbaobiaoModal,
    TableMingxihuizongModal,
    ChooseCustomerModal,
    ExportProjectModal,
    ExportEmployeeModal,
    ChooseExportTemplateModal
  },

  data () {
    return {
      searchCompanyName: [],
      thead: _cloneDeep(billMergeThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      slotArr: [
        { slot: 'shebaomingxi', text: '社保明细', type: 'text', fn: 'handleShowTableShebaomingxiModal' },
        { slot: 'gongjijinmingxi', text: '公积金明细', type: 'text', fn: 'handleShowTableGongjijinmingxiModal' },
        { slot: 'shangbaomingxi', text: '商保明细', type: 'text', fn: 'handleShowTableShangbaomingxiModal' },
        { slot: 'xinzimingxi', text: '薪资明细', type: 'text', fn: 'handleShowTableXinzimingxiModal' },
        { slot: 'fuwufeimingxi', text: '服务费明细', type: 'text', fn: 'handleShowTableFuwufeimingxiModal' },
        { slot: 'mingxihuizong', text: '明细汇总', type: 'text', fn: 'handleShowTableMingxihuizongModal' },
        { slot: 'shebaohuizong', text: '社保汇总', type: 'text', fn: 'handleShowTableShebaohuizongModal' },
        { slot: 'fuwufeihuizong', text: '服务费汇总', type: 'text', fn: 'handleShowTableFuwufeihuizongModal' },
        { slot: 'huizongbaobiao', text: '汇总报表', type: 'text', fn: 'handleShowTableHuizongbaobiaoModal' }
        // {slot: 'shujuhedui', text: '核对完成', type: 'info', fn: 'handleShowDatacheckModal'},
        // {slot: 'shenqingkaipiao', text: '申请开票', type: 'info', fn: 'handleShowApplyInvoiceModal'}
      ],
      formData: {
        customerIds: [],
        beginTime: this.$moment(new Date()).format('YYYY-MM'),
        endTime: this.$moment(new Date()).format('YYYY-MM'),
      },
      arrListDown: {
        customer: []
      },
      isShowTable: false,
      selectCustomerIds: [],
      selectCustomerIdsStr: ''
    }
  },

  watch: {
  },

  mounted () {
    var that = this
    // this.query()
    this.companys()
    // this.getCustomerArr()
    setTimeout(() => {
      that.getCustomerArr()
    }, 1000);
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 核对完成
    hasBillCheck () {
      return this.actionArr.indexOf('BillCheck') > -1
    },
    // 申请开票
    hasPostInvoice () {
      return this.actionArr.indexOf('PostInvoice') > -1
    },
    // 导出客户数据汇总
    hasExportCustomerSummary () {
      return this.actionArr.indexOf('ExportCustomerSummary') > -1
    },
    // 导出客户数据明细
    hasExportCustomerSummaryDetail () {
      return this.actionArr.indexOf('ExportCustomerSummaryDetail') > -1
    },
    // 导出员工数据汇总
    hasExportEmployeeSummary () {
      return this.actionArr.indexOf('ExportEmployeeSummary') > -1
    },
    // 导出员工数据明细
    hasExportEmployeeSummaryDetail () {
      return this.actionArr.indexOf('ExportEmployeeSummaryDetail') > -1
    }
  },

  methods: {
    // 获取公司
    async companys () {
      var params = {
        PageIndex: 1,
        PageSize: 10000,
        Args: ''
      }
      Common.companys(params, this.arrListDown, 'customer')
    },

    getCustomerArr () {
      var arr = []
      this.arrListDown.customer.map(item => {
        arr.push({ label: item.label, key: item.value })
      })
      this.$refs.ChooseCustomerModal.customer = arr
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    // 日期选择
    datePickerChange (e) {
      this.formData.month = e
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ', model)
      console.log('val: ', val)
      this.formData[model] = val
    },

    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      console.log('this.selectCustomerIds: ', this.selectCustomerIds)
      this.searchCompanyName = []
      this.arrListDown.customer.map(item => {
        if (this.selectCustomerIds.indexOf(item.value) !== -1) {
          this.searchCompanyName.push(item.label)
        }
      })
      console.log('this.searchCompanyName: ', this.searchCompanyName)

      var params = {
        CompanyIds: this.selectCustomerIds.join(','),
        BeginTime: this.$moment(this.formData.beginTime).format('YYYY-MM'),
        EndTime: this.$moment(this.formData.endTime).format('YYYY-MM'),
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await MergeBillApi.getList(params)
      console.log('账单合并res: ', res)
      if (res.status === 200 && res.data.success) {
        if (res.data.data) {
          this.isShowTable = true
          this.tableData = res.data.data
          this.tableComone.totalRows = res.data.totalRows
        } else {
          this.$Message.warning({
            content: '无相关数据',
            // duration: 0,
            closable: true
          })
        }
      } else {
        this.isShowTable = false
        this.tableData = []
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.loading = false
      console.log('this.tableData: ', this.tableData)
    },

    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
      console.log('...values: ', ...values)
    },

    // 显示弹窗-服务费汇总表格
    handleShowTableFuwufeihuizongModal (row) {
      this.$refs.TableFuwufeihuizongModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableFuwufeihuizongModal.isShowTableFuwufeihuizongModal = true
      this.queryTableVal(this.$refs.TableFuwufeihuizongModal, row)
    },

    // 显示弹窗-服务费明细表格
    handleShowTableFuwufeimingxiModal (row) {
      this.$refs.TableFuwufeimingxiModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableFuwufeimingxiModal.isShowTableFuwufeimingxiModal = true
      this.queryTableVal(this.$refs.TableFuwufeimingxiModal, row)
    },

    // 显示弹窗-明细汇总表格
    handleShowTableMingxihuizongModal (row) {
      this.$refs.TableMingxihuizongModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableMingxihuizongModal.idCardNo = null
      this.$refs.TableMingxihuizongModal.isShowTableMingxihuizongModal = true
      this.queryTableVal(this.$refs.TableMingxihuizongModal, row)
    },

    // 显示弹窗-薪资明细表格
    handleShowTableXinzimingxiModal (row) {
      this.$refs.TableXinzimingxiModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableXinzimingxiModal.isShowTableXinzimingxiModal = true
      this.queryTableVal(this.$refs.TableXinzimingxiModal, row)
    },

    // 显示弹窗-商保明细表格
    handleShowTableShangbaomingxiModal (row) {
      this.$refs.TableShangbaomingxiModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableShangbaomingxiModal.isShowTableShangbaomingxiModal = true
      this.queryTableVal(this.$refs.TableShangbaomingxiModal, row)
    },

    // 显示弹窗-公积金明细表格
    handleShowTableGongjijinmingxiModal (row) {
      this.$refs.TableGongjijinmingxiModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableGongjijinmingxiModal.isShowTableGongjijinmingxiModal = true
      this.queryTableVal(this.$refs.TableGongjijinmingxiModal, row)
    },

    // 显示弹窗-社保明细表格
    handleShowTableShebaomingxiModal (row) {
      this.$refs.TableShebaomingxiModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableShebaomingxiModal.isShowTableShebaomingxiModal = true
      this.queryTableVal(this.$refs.TableShebaomingxiModal, row)
    },

    // 显示弹窗-社保汇总表格
    handleShowTableShebaohuizongModal (row) {
      this.$refs.TableShebaohuizongModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableShebaohuizongModal.isShowTableShebaohuizongModal = true
      this.queryTableVal(this.$refs.TableShebaohuizongModal, row)
    },

    // 显示弹窗-汇总报表表格
    handleShowTableHuizongbaobiaoModal (row) {
      this.$refs.TableHuizongbaobiaoModal.companyName = this.searchCompanyName.join(',')
      this.$refs.TableHuizongbaobiaoModal.isShowTableHuizongbaobiaoModal = true
      this.queryTableVal(this.$refs.TableHuizongbaobiaoModal, row)
      // this.$refs.TableHuizongbaobiaoModal.customerPayInfo()
    },

    // 表格弹窗公用赋值
    queryTableVal (modal, row) {
      modal.tableData = []
      modal.companyId = this.selectCustomerIds
      modal.year = row.periodYear
      modal.month = row.periodMonth
      // modal.billDate = this.$moment(this.formData.month).format('YYYY-MM')
      const month = row.periodMonth < 10 ? '0' + row.periodMonth : '' + row.periodMonth
      modal.billDate = row.periodYear + '-' + month
      modal.query()
    },

    // 单位选择
    handleCustomerIdsChange (val) {
      console.log('🧞‍ val: ', val)
      this.selectCustomerIds = val
      this.selectCustomerIdsStr = val.join(',')
    },

    // 显示弹窗-汇总报表表格
    handleShowChooseCustomerModal (row) {
      this.$refs.ChooseCustomerModal.targetKeys = this.formData.customerIds
      this.$refs.ChooseCustomerModal.show()
    },

    // 确定选择查询单位
    chooseSubmit (arr) {
      console.log('🚩🚩🚩 arr: ', arr)
      this.formData.customerIds = arr
      this.handleCustomerIdsChange(arr)
    },

    // 显示弹窗-选择项目
    handleShowExportProjectModal () {
      this.$refs.ExportProjectModal.show()
      this.$refs.ExportProjectModal.companyIds = this.formData.customerIds
      this.$refs.ExportProjectModal.beginTime = this.formData.beginTime
      this.$refs.ExportProjectModal.endTime = this.formData.endTime
    },

    // 显示弹窗-选择员工
    handleShowExportEmployeeModal (pageType, modalKey) {
      this.$refs.ExportEmployeeModal.modalKey = modalKey
      this.$refs.ExportEmployeeModal.pageType = pageType
      this.$refs.ExportEmployeeModal.companyIds = this.formData.customerIds.join(',')
      this.$refs.ExportEmployeeModal.beginTime = this.formData.beginTime
      this.$refs.ExportEmployeeModal.endTime = this.formData.endTime
      this.$refs.ExportEmployeeModal.show()
      this.$refs.ExportEmployeeModal.getUserList()
    },

    async handleExportCustomerSummary () {
      var params =  {
        companyIds: this.formData.customerIds.join(','),
        beginTime: this.formData.beginTime,
        endTime: this.formData.endTime,
      }
      let res = await MergeBillApi.exportCustomerSummary(params)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.data)
        window.open(baseUrl + res.data.data, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 选择导出模板 弹窗-显示
    handleShowChooseExportTemplateModal (month) {
      console.log('账单详情 触发了父组件里的方法', month)
      this.$refs.ChooseExportTemplateModal.show(22, month, this.formData.customerIds.join(','))
      this.$refs.ChooseExportTemplateModal.getExportList()
    },

    // 确定选择导出模板
    chooseTemplate (templateId) {
      console.log('确定选择导出模板: ', templateId)
      this.$refs.TableXinzimingxiModal.exportSalaryDetailList(templateId)
    }
  } // methods end
}
</script>

<style lang="less" scope>
</style>
